package com.hn.shopadmin.conf;


import com.alibaba.fastjson.JSON;
import com.hn.kiss.modules.sys.shopcommon.common.MyException;
import com.hn.kiss.modules.sys.shopcommon.common.ParmException;
import com.hn.kiss.modules.sys.shopcommon.result.CommonResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by Administrator on 2017/12/11.
 * 全局异常处理
 */
@Configuration
public class MyExceptionHandler implements HandlerExceptionResolver {
	
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception ex) {
    	Logger logger = LoggerFactory.getLogger(o.getClass());
    	ModelAndView mv = new ModelAndView();
        CommonResult result = null;
        if (ex instanceof MyException) {//自定义异常
        	result = CommonResult.failed(ex.getMessage());
        	logger.info(ex.getMessage());
        }else if (ex instanceof ParmException) {//参数异常
			result = CommonResult.validateFailed(ex.getMessage());
			logger.info(ex.getMessage());
		}else {//系统异常
        	ex.printStackTrace();
        	result = CommonResult.failed(ex.getMessage());
        	for(StackTraceElement s : ex.getStackTrace()) {
        		logger.error(s.toString());
        	}
           
        }
        //将信息写到前台
        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json; charset=utf-8");
        PrintWriter writer;
		try {
			writer = httpServletResponse.getWriter();
			writer.write(JSON.toJSONString(result));
		    writer.close();
		} catch (IOException e) {
			logger.error("连接客户端异常："+e.getMessage(),e);
		}
       
        return mv;
    }
}
